<template>
  <div class="file-download-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <div class="search-container">
        <el-input
          v-model="searchQuery.keyword"
          placeholder="请输入文件名或描述"
          clearable
          @clear="handleSearch"
          class="search-input"
        />
        <el-button
          type="primary"
          @click="handleSearch"
          icon="el-icon-search"
          class="search-button"
        >
          搜索
        </el-button>
        <el-button
        v-if="isAdmin"
        type="success"
        icon="el-icon-upload"
        @click="showUploadDialog"
        class="upload-button"
        >
        上传模板
        </el-button>
      </div>
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog
      title="上传模板文件"
      :visible.sync="uploadVisible"
      width="30%"
    >
      <el-form>
        <el-upload
          :auto-upload="false"
          ref="upload"
          class="upload-demo"
          drag
          :action="uploadUrl"
          :headers="uploadHeaders"
          :data="uploadData"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
          :show-file-list="false"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
        </el-upload>
        <el-form-item label="文件描述">
          <el-input
            v-model="uploadData.description"
            type="textarea"
            rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 文件列表 -->
    <el-card class="file-list-card">
      <el-table
        :data="fileList"
        stripe
        style="width: 100%"
        v-loading="loading"
        empty-text="暂无文件模板"
      >
        <!-- 文件名列修改 -->
        <el-table-column prop="filename" label="文件名" min-width="200">
          <template slot-scope="{ row }">
            {{ formatFilename(row.filename) }}
          </template>
        </el-table-column>
        <!-- 调整列宽 -->
        <el-table-column prop="description" label="描述" min-width="300" :show-overflow-tooltip="false">
          <template slot-scope="{ row }">
            <div class="description-cell">{{ row.description }}</div>
          </template>
        </el-table-column>
        <!-- 文件类型列修改 -->
        <el-table-column label="文件类型" width="100">
          <template slot-scope="{ row }">
            <el-tag effect="plain">{{ formatFileType(row.filetype) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" width="120">
          <template slot-scope="{ row }">
            {{ formatFileSize(row.filesize) }}
          </template>
        </el-table-column>
        <el-table-column label="上传时间" width="180">
          <template slot-scope="{ row }">
            {{ formatTime(row.uploadtime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              size="mini"
              @click="handleDownload(row)"
            >
              下载
            </el-button>
            <el-button
              v-if="isAdmin"
              type="danger"
              size="mini"
              @click="handleDelete(row.fileid)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @current-change="handlePageChange"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next, jumper"
      />
    </el-card>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import axios from 'axios'

export default {
  name: 'FileDownload',
  data() {
    return {
      searchQuery: {
        keyword: ''
      },
      uploadVisible: false,
      uploadData: {
        description: '',
        uploaderId: null
      },
      fileList: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      uploadUrl: '/file-template/upload',
      uploadHeaders: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    }
  },
  computed: {
    isAdmin() {
      const role = localStorage.getItem('role')
      return role === '超级管理员' || role === '管理员'
    }
  },
  created() {
    this.loadFiles()
    this.uploadData.uploaderId = parseInt(localStorage.getItem('userid'))
  },
  methods: {
    //简化文件类型
    formatFileType(filetype) {
      const typeMap = {
        'application/pdf': 'PDF',
        'application/msword': 'Word',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Word',
        'application/vnd.ms-excel': 'Excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'Excel',
        'text/plain': 'TXT'
      };
      return typeMap[filetype] || filetype.split('/').pop().toUpperCase();
    },
    // 去除UUID
    formatFilename(filename) {
      // 按第一个下划线分割，取后半部分
      const parts = filename.split('_');
      return parts.length > 1 ? parts.slice(1).join('_') : filename;
    },
    // 加载文件数据
    async loadFiles() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          keyword: this.searchQuery.keyword
        }

        const response = await axios.get('/file-template/list', { params })
        this.fileList = response.data.list
        this.pagination.total = response.data.total
      } catch (error) {
        const errorMessage = (error.response && error.response.data && error.response.data.message) || '网络错误'
        Message.error('文件加载失败：' + errorMessage)
      } finally {
        this.loading = false
      }
    },

    // 处理搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.loadFiles()
    },

    // 处理分页
    handlePageChange(page) {
      this.pagination.currentPage = page
      this.loadFiles()
    },

    // 显示上传对话框
    showUploadDialog() {
      this.uploadVisible = true
    },

    // 上传前校验
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        Message.error('文件大小不能超过10MB')
        return false
      }
      return true
    },

    // 提交上传
    submitUpload() {
      if (!this.uploadData.description) {
        Message.warning('请输入文件描述');
        return;
      }

      const formData = new FormData();
      const file = this.$refs.upload.uploadFiles[0].raw;
      formData.append('file', file);
      formData.append('description', this.uploadData.description);
      // 修改参数名为 uploaderId（与后端 @RequestParam 一致）
      formData.append('uploaderId', this.uploadData.uploaderId.toString()); // 显式转换为字符串

      axios.post('/file-template/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      }).then(res => {
        this.handleUploadSuccess(res.data);
      }).catch(error => {
        Message.error('上传失败: ' + error.message);
      });
    },

    // 处理上传成功
    handleUploadSuccess(res) {
      if (res.state === 'success') {
        Message.success('上传成功')
        this.uploadVisible = false
        this.loadFiles()
      } else {
        Message.error(res.message || '上传失败')
      }
    },

    // 处理删除
    async handleDelete(fileId) {
      try {
        await this.$confirm('确认删除该模板吗？', '提示', { type: 'warning' })
        await axios.delete(`/file-template/${fileId}`)
        Message.success('删除成功')
        this.loadFiles()
      } catch (error) {
        if (error !== 'cancel') {
          const errorMessage = (error.response && error.response.data && error.response.data.message) || '删除失败'
          Message.error(errorMessage)
        }
      }
    },

    // 处理下载
    handleDownload(file) {
      const encodedFilename = encodeURIComponent(file.filename);
      this.$axios.get('/file-template/download', {
        params: {
          filename: encodedFilename
        },
        responseType: 'blob'
      })
        .then(response => {
          const blob = new Blob([response.data])
          const downloadUrl = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          const filename = this.formatFilename(file.filename)

          link.href = downloadUrl
          link.download = filename
          link.style.display = 'none'

          document.body.appendChild(link)
          link.click()

          window.URL.revokeObjectURL(downloadUrl)
          document.body.removeChild(link)
        })
        .catch(error => {
          // 修改后的错误处理
          const errorMessage = (error.response
            && error.response.data
            && error.response.data.message) || '文件下载失败'
          Message.error(errorMessage)

          // 修改后的Blob类型检查
          if (error.response
            && error.response.data
            && error.response.data instanceof Blob) {
            const reader = new FileReader()
            reader.onload = () => {
              try {
                const errorData = JSON.parse(reader.result)
                Message.error(`错误详情：${errorData.message}`)
              } catch (e) {
                console.error('解析错误信息失败', e)
              }
            }
            reader.readAsText(error.response.data)
          }
        })
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
    },

    // 格式化时间
    formatTime(isoTime) {
      if (!isoTime) return ''
      const date = new Date(isoTime)
      const pad = num => num.toString().padStart(2, '0')
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
    }
  }
}
</script>

<style scoped>

/* 调整行高和换行 */
.el-table /deep/ .cell {
  white-space: pre-line; /* 允许换行 */
  line-height: 1.6; /* 增加行高 */
}

/* 描述列最大高度 */
.description-cell {
  max-height: 100px;
  overflow-y: auto;
}

/* 调整列间距 */
.el-table--fit {
  border-spacing: 0 8px; /* 行间距 */
}

/* 调整表格整体高度 */
.el-table {
  min-height: 400px;
}

.file-download-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  gap: 10px;
}

.search-input {
  flex: 1;
}

.file-list-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.upload-demo {
  text-align: center;
  margin-bottom: 20px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .search-container {
    flex-direction: column;
  }

  .search-button {
    width: 100%;
  }
}
</style>
